//
//  UIColor-Extension.swift
//  APP0517
//
//  Created by Li Shengbing, (Shengbing.Li@partner.bmw.com) on 2019/5/27.
//  Copyright © 2019年 Li Shengbing, (Shengbing.Li@partner.bmw.com). All rights reserved.
//

import UIKit

extension UIColor {
    
    
    /// through hex string covert to UIColor
    ///
    /// - Parameter hexString: "0xffffff" || "#ffffff" || "0Xffffff"
    /// - Returns: UIColor
    public static func hexStringToColor(hexString: String) -> UIColor{
        var cString: String = hexString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
        
        if cString.count < 6 {
            print("\"*****hexStringToColor*****\": \n   hexString.count < 6.\n\"*****hexStringToColor*****\"")
            return UIColor.black
        }
        if cString.hasPrefix("0X") || cString.hasPrefix("0x") {
            cString = String(cString[cString.index(cString.startIndex, offsetBy: 2)...])
            //cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 2))
        }
        if cString.hasPrefix("#") {
            cString = String(cString[cString.index(cString.startIndex, offsetBy: 1)...])
            //cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1))
        }
        if cString.count != 6 {
            print("\"*****hexStringToColor*****\": \n   hexString.count != 6.\n\"*****hexStringToColor*****\"")
            return UIColor.black
        }
        
        var range: NSRange = NSMakeRange(0, 2)
        let rString = (cString as NSString).substring(with: range)
        range.location = 2
        let gString = (cString as NSString).substring(with: range)
        range.location = 4
        let bString = (cString as NSString).substring(with: range)
        
        var r: UInt32 = 0x0
        var g: UInt32 = 0x0
        var b: UInt32 = 0x0
        Scanner.init(string: rString).scanHexInt32(&r)
        Scanner.init(string: gString).scanHexInt32(&g)
        Scanner.init(string: bString).scanHexInt32(&b)
        
        if #available(iOS 10.0, *) {
            return UIColor(displayP3Red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(1))
        } else {
            // Fallback on earlier versions
            return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: CGFloat(1))
        }
    }
}
